package com.athuahua.mq.config;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Configuration;

/**
 * @Author: huahua
 * @Date: 2024/9/3 0003
 * @Time: 14:03
 * @Description:
 */
@Configuration
@Slf4j
public class RabbitConfig implements RabbitTemplate.ConfirmCallback , RabbitTemplate.ReturnsCallback {

    @Resource
    private RabbitTemplate rabbitTemplate;

    @PostConstruct //对象创建之后立即执行的方法
    public void initRabbitTemplate() {
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnsCallback(this);
    }


    /**
     * ConfirmCallback 接口的实现，用于消息发送到交换机成功或失败的确认。
     * @param correlationData 包含消息相关信息的对象
     * @param ack 返回true表示消息发送成功，false表示消息发送失败
     * @param cause 返回失败的原因
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        // 消息发送到交换机成功或失败都会调用这个方法
        log.info("回调函数打印：correlationData:{},ack:{}" , correlationData, ack);
        if(!ack)
            log.info("失败原因: cause" + cause);

    }

    @Override
    public void returnedMessage(ReturnedMessage returnedMessage) {
        // 只有消息发送到队列失败才会调用这个方法
        log.info("消息主体: " + new String(returnedMessage.getMessage().getBody()));
        log.info("应答码: " + returnedMessage.getReplyCode());
        log.info("回复文本: " + returnedMessage.getReplyText());
        log.info("交换机 exchange: " + returnedMessage.getExchange());
        log.info("路由键 routing key: " + returnedMessage.getRoutingKey());

    }
}
